package com.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.constant.MessageConstant;
import com.entity.Result;
import com.service.MemberService;
import com.service.ReportService;
import com.service.SetmealService;
import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.apache.ibatis.annotations.ResultMap;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@RequestMapping("/report")
@RestController
public class ReportController {
    @Reference
    MemberService memberService;
    @Reference
    SetmealService setmealService;
    @Reference
    ReportService reportService;
    @RequestMapping("/getMemberReport")
    public Result getMember(){
        Calendar cal = Calendar.getInstance();
        System.out.println(cal);
        System.out.println("-------------");
        System.out.println(cal.getTime());
        cal.add(Calendar.MONTH,-12);//获得当前日期之前12个月的日期
        List<String> list=new ArrayList<>();
        for (int i = 0; i < 12; i++) {
          cal.add(Calendar.MONTH,1);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM");
            String date = sdf.format(cal.getTime());
            list.add(date);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("months",list);
        Result result=null;
        try {
            List<Integer> ll=memberService.getMemberData(list);
            map.put("memberCount",ll);
            result= new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS,map);
        } catch (Exception e) {
            e.printStackTrace();
            result=new Result(false,"查询数据失败了");
        }
        return result;
    }
    @RequestMapping("/getSetmealReport")
    public Result getSetmealReport(){
        Result result = null;
        try {
            result = setmealService.getSetmealReport();
        } catch (Exception e) {
            e.printStackTrace();
            result=new Result(false,MessageConstant.GET_SETMEAL_COUNT_REPORT_FAIL);
        }
        return result;
    }
    @RequestMapping("/getBusinessReportData")
    public Result getBusinessReportData(){
        Result result= null;
        try {
            result = reportService.getBusinessReportData();
        } catch (Exception e) {
            e.printStackTrace();
            result=new Result(false,"系统出现异常");
        }
        return result;
    }
    @RequestMapping("/exportBusinessReport")
    public Result exportBusinessReport(HttpServletRequest request, HttpServletResponse response){
        //数据准备好
        Map result = (Map)getBusinessReportData().getData();
        //取出返回结果数据，准备将报表数据写入到Excel文件中
        String reportDate = (String) result.get("reportDate");
        Integer todayNewMember = (Integer) result.get("todayNewMember");
        Integer totalMember = (Integer) result.get("totalMember");
        Integer thisWeekNewMember = (Integer) result.get("thisWeekNewMember");
        Integer thisMonthNewMember = (Integer) result.get("thisMonthNewMember");
        Integer todayOrderNumber = (Integer) result.get("todayOrderNumber");
        Integer thisWeekOrderNumber = (Integer) result.get("thisWeekOrderNumber");
        Integer thisMonthOrderNumber = (Integer) result.get("thisMonthOrderNumber");
        Integer todayVisitsNumber = (Integer) result.get("todayVisitsNumber");
        Integer thisWeekVisitsNumber = (Integer) result.get("thisWeekVisitsNumber");
        Integer thisMonthVisitsNumber = (Integer) result.get("thisMonthVisitsNumber");
        List<Map> hotSetmeal = (List<Map>) result.get("hotSetmeal");
        //数据导入
        String realPath = request.getSession().getServletContext().getRealPath("template" + File.separator + "report_template.xlsx");
        //poi工具去读取模板,加载到内存中
        try {
            XSSFWorkbook excel = new XSSFWorkbook(new FileInputStream(new File(realPath)));
            XSSFSheet sheet = excel.getSheetAt(0);
            XSSFRow row = sheet.getRow(2);
            XSSFCell cell = row.getCell(5);
            cell.setCellValue(reportDate);//日期
            XSSFRow row1 = sheet.getRow(4);
            row1.getCell(5).setCellValue(todayNewMember);//新增会员数（本日）
            row1.getCell(7).setCellValue(totalMember);//总会员数
            XSSFRow row2 = sheet.getRow(5);
            row2.getCell(5).setCellValue(thisWeekNewMember);//本周新增会员数
            row2.getCell(7).setCellValue(thisMonthNewMember);//本月新增会员数
            row = sheet.getRow(7);
            row.getCell(5).setCellValue(todayOrderNumber);//今日预约数
            row.getCell(7).setCellValue(todayVisitsNumber);//今日到诊数
            row = sheet.getRow(8);
            row.getCell(5).setCellValue(thisWeekOrderNumber);//本周预约数
            row.getCell(7).setCellValue(thisWeekVisitsNumber);//本周到诊数

            row = sheet.getRow(9);
            row.getCell(5).setCellValue(thisMonthOrderNumber);//本月预约数
            row.getCell(7).setCellValue(thisMonthVisitsNumber);//本月到诊数
            int rows=12;
            for (Map map : hotSetmeal) {
                String name = (String) map.get("name");
                Long setmeal_count = (Long) map.get("setmeal_count");
                BigDecimal proportion = (BigDecimal) map.get("proportion");
                XSSFRow row3 = sheet.getRow(rows++);
                row3.getCell(4).setCellValue(name);
                row3.getCell(5).setCellValue(setmeal_count);//预约数量
                row3.getCell(6).setCellValue(proportion.doubleValue());//占比
            }
            //表格数据已经在内存中合并完成现在开始输出给浏览器
            ServletOutputStream os = response.getOutputStream();
            response.setContentType("application/vnd.ms-excel");//代表的是Excel文件类型
            response.setHeader("content-Disposition","attachment;filename=report.xlsx");
            excel.write(os);
            os.flush();
            os.close();
            excel.close();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(false,"下载失败了");
        }
    }
    @RequestMapping("/exportBusinessReportPDF")
    public Result exportBusinessReportPDF(HttpServletRequest request,HttpServletResponse response){
        //数据准备好
        Map result = (Map)getBusinessReportData().getData();
        //取出返回结果热门数据准备写入到PDF中
        List<Map> list=(List<Map>)result.get("hotSetmeal");
        //获取模板具体位置
        String jrxmlPath = request.getSession().getServletContext().getRealPath("template" + File.separator + "health_business3.jrxml");
        //编写字节码文件生成位置
        String jasperPath = request.getSession().getServletContext().getRealPath("template" + File.separator + "health_business3.jasper");
        //编译模板
        try {
            JasperCompileManager.compileReportToFile(jrxmlPath,jasperPath);
        //填充数据--
            JasperPrint jasperPrint = JasperFillManager.fillReport(jasperPath, result, new JRBeanCollectionDataSource(list));
            //准备输出文件
            response.setContentType("application/pdf");
            response.setHeader("content-Disposition","attachment;filename=report.pdf");
            //开始输出文件
            ServletOutputStream out = response.getOutputStream();
            JasperExportManager.exportReportToPdfStream(jasperPrint,out);
            out.flush();
            out.close();
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,"查询失败");
        }

    }
}
